package edu.hcmus.sow.web;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.validation.Errors;

import edu.hcmus.sow.dao.SiteDAO;
import edu.hcmus.sow.domain.Site;

public class ClientForm {
   private Integer id;
   @NotEmpty(message = "Name must not be blank.")
   private String name;
   @NotEmpty(message = "Sub Domain must not be blank.")
   private String subDomain;
   private Boolean status;
   private String email;
   private String phone;

   public Integer getId() {
      return id;
   }

   public void setId(Integer id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getSubDomain() {
      return StringUtils.isEmpty(subDomain) ? subDomain : subDomain.trim().replace(' ', '_').toLowerCase();
   }

   public void setSubDomain(String subDomain) {
      this.subDomain = subDomain;
   }

   public Boolean getStatus() {
      return status;
   }

   public void setStatus(Boolean status) {
      this.status = status;
   }

   public String getEmail() {
      return email;
   }

   public void setEmail(String email) {
      this.email = email;
   }

   public String getPhone() {
      return phone;
   }

   public void setPhone(String phone) {
      this.phone = phone;
   }

   public void validate(Errors errors, SiteDAO siteDAO) {
      if (!errors.hasFieldErrors("subDomain")) {
         Site site = siteDAO.findBySubDomain(getSubDomain());
         int clientId = (id == null) ? -1 : id.intValue();
         if (site != null && site.getClient().getId().intValue() != clientId) {
            errors.rejectValue("subDomain", "err.subDomain", "Sub Domain already exists.");
         }
      }
   }
}
